package user.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import core.constants.Constant;
import core.enums.ResultCode;
import core.exception.ServiceException;
import core.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import user.domain.question.Question;
import user.domain.question.vo.RankVO;
import user.mapper.CQuestionMapper;

import java.util.List;

@Component
public class QuestionCacheManage {
    @Autowired
    private RedisService redisService;

    @Autowired
    private CQuestionMapper questionMapper;
    public long getQuestionCount() {
        return redisService.getListSize(Constant.QUESTION_LIST);
    }


    public void refreshQuestion() {
        List<Question> questionList = questionMapper
                .selectList(new LambdaQueryWrapper<Question>()
                        .orderByDesc(Question::getCreateTime));
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        List<Long> questionIdList = questionList.stream().map(Question::getQuestionId).toList();
        redisService.rightPushAll(Constant.QUESTION_LIST, questionIdList);

    }

    public Long preQuestion(Long questionId) {
        Long index = redisService.indexOfForList(Constant.QUESTION_LIST, questionId);
        if (index <= 0) {
            throw new ServiceException(ResultCode.FIRST_QUESTION);
        }
        return redisService.indexForList(Constant.QUESTION_LIST, index - 1, Long.class);
    }

    public Long nextQuestion(Long questionId) {
        Long index = redisService.indexOfForList(Constant.QUESTION_LIST, questionId);
        if (index >= getQuestionCount() -1) {
            throw new ServiceException(ResultCode.LAST_QUESTION);
        }
        return redisService.indexForList(Constant.QUESTION_LIST, index + 1, Long.class);
    }

    public long getTopRankCount() {
        return redisService.getListSize(Constant.TOP_RANK_LIST);
    }

    public void refreshTopRank(List<RankVO> topFiveRank) {
        redisService.rightPushAll(Constant.TOP_RANK_LIST, topFiveRank);
    }

    public List<RankVO> topRank() {
        return redisService.getCacheListByRange(Constant.TOP_RANK_LIST, 0, -1, RankVO.class);
    }
}
